package openai

import (
	"chatgpt/helper/code"
	"context"
	gogpt "github.com/sashabaranov/go-openai"
	"github.com/slclub/glog"
	"github.com/slclub/go-tips"
)

func (self *AppGPT) CreateImage(question *RequestImage) *ResponseImage {
	ctx := context.Background()
	response := &ResponseImage{
		MsgCode: code.SUCCESS,
	}
	if question.Text == "" {
		response.MsgCode = code.DATA_NIL
		glog.Errorf("CHATGPT.CreateImage.REQ.TEXT is empty!")
		return response
	}

	prompt := question.Text

	glog.Infof("CHATGPT.CreateImage.REQ prompt is %s", prompt)
	//req := gogpt.CompletionRequest{
	//	Model:            cnf.Model,
	//	MaxTokens:        cnf.MaxTokens,
	//	TopP:             cnf.TopP,
	//	FrequencyPenalty: cnf.FrequencyPenalty,
	//	PresencePenalty:  cnf.PresencePenalty,
	//	Prompt:           prompt,
	//}
	if question.N <= 0 {
		question.N = 1
	}
	if question.Size == "" || len(question.Size) < 3 || tips.StrPos(question.Size, "x") <= 0 {
		question.Size = "256x256"
	}
	req := gogpt.ImageRequest{
		Prompt: question.Text,
		N:      question.N,
		Size:   question.Size,
	}

	resp, err := self.Client().CreateImage(ctx, req)
	response.resp = resp
	if err != nil {
		glog.Errorf("CHATGPT.CreateImage.RESPONSE.ERROR %v", err)
		response.MsgCode = code.DATA_CALL_ERROR
		return response
	}
	glog.Debugf("CHATGPT.CreateImage.RESPONSE.OK")
	return response
}

func (self *AppGPT) ConvImage(question string, size string) *Response {
	result := &Response{}
	res := AppChatGPT.CreateImage(&RequestImage{Text: question, Size: size})
	result.MsgCode = res.MsgCode
	if result.MsgCode != code.SUCCESS {
		return result
	}
	if len(res.resp.Data) == 0 {
		return result
	}
	data := res.resp.Data[0].URL
	if data == "" {
		data = res.resp.Data[0].B64JSON
	}
	result.Text = data
	result.Tokens = 999999
	return result
}
